package com.fjnldx.mes.service.monitor;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjnldx.mes.domain.domainReq.*;
import com.fjnldx.mes.domain.domainRes.QueryResult;
import com.fjnldx.mes.domain.domainRes.Result;
import com.fjnldx.mes.domain.domainRes.XsRealTimeDataOfQuery;
import com.fjnldx.mes.domain.pojo.HistoricalDataQueryInfo;
import com.fjnldx.mes.mapper.monitor.MonitorMapper;
import com.fjnldx.mes.service.historicalData.HistoricalDataService;
import com.fjnldx.mes.utils.Common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 监控中心
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MonitorService {
    @Resource
    private Common common;
    @Resource
    MonitorMapper monitorMapper;
    @Resource
    HistoricalDataService historicalDataService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 车台实时数据-数据字典-级联1
     *
     * @param data
     * @return
     * @throws Exception
     */
    public Result getRealTimeDataOfDictionariesOne(DictionariesOne data) throws Exception {
        try {
            List<DictionariesOneReturn> list = monitorMapper.getRealTimeDataOfDictionariesOne(data);
            return Result.success(list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 车台实时数据-数据字典-级联2
     *
     * @param data
     * @return
     * @throws Exception
     */
    public Result getRealTimeDataOfDictionariesTwo(DictionariesTwo data) throws Exception {
        try {
            List<DictionariesTwoReturn> list = monitorMapper.getRealTimeDataOfDictionariesTwo(data);
            return Result.success(list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 不同工序-车台实时数据
     */
    public QueryResult realTimeData(XsRealTimeDataOfQuery query) throws Exception {
        try {
            switch (query.getGongxu()) {
                case "细纱":
                    List<Map<String, Object>> run = monitorMapper.getXsRealTimeDataOfRun(query);
                    Integer runTotal = monitorMapper.getTotalXsRealTimeDataOfRun(query);
                    return QueryResult.success(run, runTotal);
                case "粗纱":
                    List<Map<String, Object>> cs = monitorMapper.getCsRealTimeDataOfRun(query);
                    Integer csTotal = monitorMapper.getTotalCsRealTimeDataOfRun(query);
                    return QueryResult.success(cs, csTotal);
                case "新粗纱":
                    List<Map<String, Object>> csNew = monitorMapper.getCsRealTimeDataOfRunNew(query);
                    Integer csNewTotal = monitorMapper.getTotalCsRealTimeDataOfRunNew(query);
                    return QueryResult.success(csNew, csNewTotal);
                case "抓棉":
                    List<Map<String, Object>> zmjRun = monitorMapper.getZmjRealTimeDataOfRun(query);
                    Integer zmjRunTotal = monitorMapper.getTotalZmjRealTimeDataOfRun(query);
                    return QueryResult.success(zmjRun, zmjRunTotal);
                case "多仓":
                    List<Map<String, Object>> dc = monitorMapper.getDcRealTimeData(query);
                    Integer dcTotal = monitorMapper.getTotalDcRealTimeData(query);
                    return QueryResult.success(dc, dcTotal);
                case "精开棉":
                    List<Map<String, Object>> kmj = monitorMapper.getKmjRealTimeDataOfRun(query);
                    Integer kmjTotal = monitorMapper.getTotalKmjRealTimeDataOfRun(query);
                    return QueryResult.success(kmj, kmjTotal);
                case "梳棉":
                    List<Map<String, Object>> sm = monitorMapper.getSmRealTimeData(query);
                    Integer smTotal = monitorMapper.getTotalSmRealTimeData(query);
                    return QueryResult.success(sm, smTotal);
                case "梳棉a":
                    List<Map<String, Object>> smA = monitorMapper.getSmARealTimeData(query);
                    Integer smATotal = monitorMapper.getTotalSmARealTimeData(query);
                    return QueryResult.success(smA, smATotal);
                case "并条":
                    List<Map<String, Object>> bt = monitorMapper.getBtRealTimeData(query);
                    Integer btTotal = monitorMapper.getTotalBtRealTimeData(query);
                    return QueryResult.success(bt, btTotal);
                case "络筒":
                    List<Map<String, Object>> lt = monitorMapper.getLtRealTimeDataOfGroup(query);
                    Integer ltTotal = monitorMapper.getTotalLtRealTimeDataOfGroup(query);
                    return QueryResult.success(lt, ltTotal);
                default:
                    return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 参数修改记录
     *
     * @param data
     * @return
     */
    public Result parameterModificationRecord(ParameterModificationRecord data) {
        String tablePrefix = null;
        List<String> daysBySection = common.getDaysBySectionAndFormat(data.getStart_time(), data.getEnd_time(), "yyyyMMdd");
        if (daysBySection.size() > 3) {
            return Result.error("只能查询连续3天的历史数据!");
        }
        List<String> tableNames = new ArrayList<>(daysBySection);
        tablePrefix = monitorMapper.historyTablePrefix(data.getGongxu(), data.getEquipment());
        if (tablePrefix == null) {
            return Result.error("暂不支持该工序的历史数据查询!");
        }

        List<HistoricalDataQueryInfo> tableNamesByQuery = this.getTableNamesByQuery(tableNames, tablePrefix,data.getGongxu(),data.getEquipment());
        if (tableNamesByQuery.size() == 0) {
            return Result.error("无该时间段数据!");
        }
        data.setTableNames(tableNamesByQuery);
        IPage<List<Map<String, Object>>> listIPage = monitorMapper.parameterModificationRecord(data);
        return Result.success(listIPage);
    }

    public List<HistoricalDataQueryInfo> getTableNamesByQuery(List<String> tableNames, String tablePrefix,String gongxu,String equipment){
        List<HistoricalDataQueryInfo> tableNamesByQuery = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime now = LocalDateTime.now();
        tableNames.forEach(table -> {
            String tableName = tablePrefix + table;
            if(common.checkTableIsExits(tableName)){
                HistoricalDataQueryInfo dataQueryInfo = new HistoricalDataQueryInfo();
                dataQueryInfo.setTableName(tableName);
                dataQueryInfo.setConditionStr(table);
                tableNamesByQuery.add(dataQueryInfo);
            }else if(dateTimeFormatter.format(now).equals(table)){
                String todayTableName = monitorMapper.mappingRelationTable(gongxu,equipment);
                if(todayTableName != null){
                    HistoricalDataQueryInfo dataQueryInfo = new HistoricalDataQueryInfo();
                    dataQueryInfo.setTableName(todayTableName);
                    dataQueryInfo.setConditionStr(table);
                    tableNamesByQuery.add(dataQueryInfo);
                }
            }
        });
        return tableNamesByQuery;
    }
}
